package main

import (
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"reflect"
)

type SignUserInfo struct {
	Name       string `json:"name" binding:"min=4,max=8" msg:"长度4-8"`
	Age        int    `json:"Age" binding:"gt=0" msg:"数字大于0"`
	Password   string `json:"Password"`
	RePassword string `json:"RePassword" binding:"eqfield=Password"`
	Sex        string `binding:"oneof=man woman"`
	//                                              dive前针对数组 dive后针对数组内元素
	LikeList []string `json:"LikeList" binding:"required,dive,required" `
	IP       string   `json:"IP" binding:"ip"`
	Url      string   `json:"Url" binding:"url"`
	Uri      string   `json:"Uri" binding:"uri"`
	Date     string   `json:"date" binding:"datetime=2006-01-02 15:04:06"`
	//`binding:"contain=f excludes=a startswith=a endswith=b"`
}

func GetValidMsg(err error, obj any) string {
	ObjReflectType := reflect.TypeOf(obj)
	if errs, ok := err.(validator.ValidationErrors); ok {
		for _, e := range errs {
			if f, exit := ObjReflectType.Elem().FieldByName(e.Field()); exit {
				msg := f.Tag.Get("msg")
				return msg
			}
		}
	}
	//未自定义信息返回默认提示词
	return err.Error()
}
func main() {
	router := gin.Default()
	var signUserInfo SignUserInfo
	router.POST("/", func(context *gin.Context) {
		err := context.ShouldBindJSON(&SignUserInfo{})
		if err != nil {
			context.JSON(200, gin.H{"msg": GetValidMsg(err, &signUserInfo)})
		}
		context.JSON(200, gin.H{"msg": "成功"})
	})
	router.Run(":8080")
}
